﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace YouTubeDownloadExtension
{
    internal sealed class VideoInfoScraper
    {
        private const string StreamMapPattern = "url_encoded_fmt_stream_map=(?<streamMap>[^&]+)";
        private const string UrlPattern = "url=(?<url>[^,]+)&quality";

        private readonly string videoInfo;
        private string streamMap;
        private IEnumerable<Uri> uris;

        public VideoInfoScraper(string videoInfo)
        {
            if (videoInfo.Contains("url_encoded_fmt_stream_map") == false)
                throw new ArgumentException("Missing stream map.", "videoInfo");
            this.videoInfo = videoInfo;
        }

        public IEnumerable<Uri> GetUris()
        {
            if (uris == null)
                throw new InvalidOperationException("Video info hasn't been extracted yet.");
            return uris;
        }

        public void ExtractData()
        {            
            ExtractStreamMapFromVideoInfo();
            ExtractUrlsFromStreamMap();            
        }        

        private void ExtractStreamMapFromVideoInfo()
        {
            var match = Regex.Match(videoInfo, StreamMapPattern);
            var encodedStreamMap = match.Groups["streamMap"].Value;
            streamMap = Uri.UnescapeDataString(encodedStreamMap);
        }

        private void ExtractUrlsFromStreamMap()
        {
            var matches = Regex.Matches(streamMap, UrlPattern);
            var encodedUrls = from Match match in matches
                              select match.Groups["url"].Value;
            uris = encodedUrls.Select(encodedUrl => new Uri(Uri.UnescapeDataString(encodedUrl)));
        }                
    }
}